<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | fastadmin: https://www.fastadmin.net/
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 手机短信接口
// +----------------------------------------------------------------------
namespace app\api\controller;

use app\api\model\Token;
use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\MemberModel;
use app\member\model\Member;
use think\facade\Hook;
use think\facade\Validate;
use think\Request;
use util\Http;

/**
 * @title 手机短信接口
 * @controller api\controller\Sms
 * @group base
 */
class Login extends Api
{

    protected $noNeedLogin = ['*'];

    public function login(){
        return 1111;
    }


    /**
     * @title 登陆
     */
    public function dyLogin(Request $request)
    {
        $params = $request->param();
        if (!isset($params['code'])) $this->error('缺失参数');
        $config = config('config_douyin.dy_program');

        $arr = [
            'appid' => $config['app_id'],
            'secret' => $config['secret'],
            'code' => $params['code'],
            'anonymous_code' => "",
        ];
        // 获取授权信息
        $url = 'https://developer.toutiao.com/api/apps/v2/jscode2session';
        // 获取信息
        $res = Http::posturl($url, $arr);
        if ($res['err_tips'] == 'success') {
            $openid = $res['data']['openid'];
            $unionid = $res['data']['unionid'];
            $time = time();
            // 查询用户信息
            $user = MemberModel::where('openid', $openid)->field('id,nickname,avatar,status')->find();
            if (empty($user)) {
                $data = [
                    'openid' => $openid,
                    'unionid' => $unionid,
                    'nickName' => urldecode($params['nickName']),
                    'avatar' => $params['avatar'],
                    'create_time' => $time,
                    'update_time' => $time
                ];
                $userId = \think\Db::name('member')->insertGetId($data);

            } else {
                if ($user['status'] == 0) {
                    $this->error('账号已被封禁，暂时无法登陆');
                }
                $userId = $user['id'];
            }
            $userInfo['user_id'] = $userId;
            $userInfo['user_token'] = (new Token())->product_token($userId, 1);
            $this->success('登陆成功',$userInfo);
        } else {
            $this->error('登录失败');
        }
    }


}
